package com.example.presenters;

import com.example.db.db;
import com.example.interfaces.IRegisterActivity;
import com.example.model.User;
import com.example.model.UserList;

/**
 * Controller that obtains a person's register information and creates a new
 * user with that information.
 * 
 * @author 3Factorial
 */
public class RegisterPresenter {

	private IRegisterActivity reg;
	private UserList users;

	/*
	 * Regexes to use for verifying user name and password requirements.
	 */
	private static String USERNAME_REGEX = "([a-z]|[A-Z])([a-z]|[A-Z]|[0-9]|_|-){4,15}";
	private static String PASSWORD_REGEX = ".{5,16}";

	/**
	 * Creates a new RegisterPresenter.
	 * 
	 * @param reg
	 *            The RegisterActivity to use.
	 * @param users
	 *            The User list to add the new user to.
	 */
	public RegisterPresenter(IRegisterActivity reg, UserList users) {
		this.reg = reg;
		this.users = users;
	}

	/**
	 * Registers a user with the information from their form.
	 * 
	 * @param username
	 *            Username to use.
	 * @param password
	 *            Password for account.
	 */
	public void register(String username, String password) {
		if (validUsername(username)) {
			if (users.userNameAvailable(username)) {
				if (validPassword(password)) {
					User newUser = new User(username, password);
					users.add(newUser);
					db dbaccess = new db();
					dbaccess.addUser(username, password, "0");
					reg.goToProfile(username);
				} else {
					reg.dispPasswordInvalid();
				}

			} else {
				reg.dispUsernameTaken();
			}
		} else {
			reg.dispUsernameInvalid();
		}

	}

	/**
	 * Determines whether the given user name is a valid user name.
	 * 
	 * @param username
	 *            Desired user name
	 * @return Trust if user name matches the criteria, false if not.
	 */
	private static boolean validUsername(String username) {
		// Changed these so that you'd just return the result of the regex.
		// It was redundant to encapsulate that in the if-statement.
		return username.matches(USERNAME_REGEX);
	}

	/**
	 * Determines whether the given password is a valid password.
	 * 
	 * @param password
	 *            Desired user password.
	 * @return Trust if password matches the criteria, false if not.
	 */
	private static boolean validPassword(String password) {
		return password.matches(PASSWORD_REGEX);
	}
}
